﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;

namespace SoftPhone
{
    public partial class frmYealinkSetting : DevExpress.XtraEditors.XtraForm
    {
        public frmYealinkSetting()
        {
            InitializeComponent();
            InitialLoad();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            System.Net.IPAddress tmp;
            if (System.Net.IPAddress.TryParse(txtYealinkIp.Text, out tmp) && System.Net.IPAddress.TryParse(txtServerIP.Text, out tmp))
            {
                YealinkConfig yealink = new YealinkConfig()
                {
                    Account = txtUserName.Text,
                    Password = txtPass.Text,
                    Extension = txtExtension.Text,
                    YealinkIp = txtYealinkIp.Text,
                    CallServerIp = txtServerIP.Text
                };

                Dictionary<string, string> config = new Dictionary<string, string>();
                string message = "";
                config.Add("YealinkUserName", txtUserName.Text);
                config.Add("YealinkPassword", txtPass.Text);
                config.Add("YealinkIp", txtYealinkIp.Text);
                config.Add("CallServerIp", txtExtension.Text);
                config.Add("YealinkExtension", txtExtension.Text);
                PolicyConfigClient.SaveConfig("Account", config, ref message);
                if (message != "")
                {
                    MessageBox.Show(message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                MessageBox.Show("Thiết lập thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            else
            {
                MessageBox.Show("Dữ liệu nhập vào không hợp lệ." + "\n" + "Xin hãy nhập lại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void InitialLoad()
        {
            var config = PolicyConfigClient.ReadConfig("Account");
            if (config != null)
            { 
                txtUserName.Text = config.Where(a=> a.Key == "YealinkUserName").SingleOrDefault().Value;
                txtPass.Text = config.Where(a => a.Key == "YealinkPassword").SingleOrDefault().Value;
                txtExtension.Text = config.Where(a => a.Key == "YealinkExtension").SingleOrDefault().Value;
                txtYealinkIp.Text = config.Where(a => a.Key == "YealinkIp").SingleOrDefault().Value;
                txtServerIP.Text = config.Where(a => a.Key == "CallServerIp").SingleOrDefault().Value;
            }
        }

    }
}